#include <QStringList>
#include <QDebug>
#include <QProcess>
#include <QApplication>
#include <QFile>
#include <QTextStream>
#include <cstdlib>

#include "settings.h"
#include "defines.h"
#include "maemo5defines.h"
#include "maemo5processrunner.h"

Maemo5ProcessRunner::Maemo5ProcessRunner(Maemo5QtProjectGenerator &generator)
    : m_process(0),
      m_generator(generator),
      m_errorWordInLogMsg(false)
{
    ;
}

Maemo5ProcessRunner::~Maemo5ProcessRunner()
{
    delete m_process;
    m_process = 0;
}


void Maemo5ProcessRunner::runApp(GeneratorPhase &generatorAction,
                                 const QStringList &params)
{
    m_generatorAction = generatorAction;
    m_errorWordInLogMsg = false;

    delete m_process;
    m_process = 0;
    m_process = new QProcess( this );
    m_process->setReadChannelMode(QProcess::MergedChannels);

    if (m_generatorAction == M5_DPKG_BUILDPACKAGE)
    {
            m_process->setWorkingDirectory(m_generator.generatorData().projectDirectory());
            if (m_generatorAction == M5_DPKG_BUILDPACKAGE)
            {
                runDpkgBuildPackage();
            }
            else
            {
                // TODO what to do, insensible state
            }
    }
    else if (m_generatorAction == M5_UNZIP_WIDGET)
    {
            runUnzip(params);
    }
}


bool Maemo5ProcessRunner::errorWordInLogMessage()
{
    return m_errorWordInLogMsg;
}


void Maemo5ProcessRunner::readProcessStdout()
{
    QProcess *pr = (QProcess*)sender();
    QString msg(pr->readAllStandardOutput());
    if (msg.contains("error ") || msg.contains("Error "))
        m_errorWordInLogMsg = true;

    m_generator.outputView().printOutput(msg);
}


void Maemo5ProcessRunner::startProcess(const QString &command,
                                        const QStringList &arguments)
{
    m_generator.outputView().printOutput("command: " + command);

    m_process->start(command, arguments);

    if (m_generator.outputView().cliOutput())
            m_process->waitForFinished(-1);
}


void Maemo5ProcessRunner::runDpkgBuildPackage()
{
    m_generator.outputView().printOutput("\n");
    m_generator.outputView().printOutput("*********************************");
    if (m_generatorAction == M5_DPKG_BUILDPACKAGE)
        m_generator.outputView().printOutput("*  Running dpkg-buildpackage");
    else
        m_generator.outputView().printOutput("*  Running no idea what TODO TODO");
    m_generator.outputView().printOutput("*********************************");
    m_generator.outputView().printOutput(m_generator.generatorData().projectDirectory());

    connect(m_process,
            SIGNAL(readyReadStandardOutput()),
            this,
            SLOT(readProcessStdout()));
    connect(m_process,
            SIGNAL(finished(int, QProcess::ExitStatus)),
            &m_generator,
            SLOT(dpkgBuildPackageFinished(int, QProcess::ExitStatus)));

    QString
        madPath = Settings::get(Settings::MaddePath).toString();
    QString
        command("cmd /C \"set PATH=%1;%PATH% & bash.exe mad dpkg-buildpackage\"");
    command = command.arg(madPath);

    m_process->start(command);

    if (m_generator.outputView().cliOutput())
            m_process->waitForFinished(-1);
}



void Maemo5ProcessRunner::runUnzip(const QStringList &params)
{
    m_generator.outputView().printOutput("\n");
    m_generator.outputView().printOutput("*********************************");
    m_generator.outputView().printOutput("*  Unzipping widget " + params[0]);
    m_generator.outputView().printOutput("*********************************");

    connect(m_process, SIGNAL(readyReadStandardOutput()), this, SLOT(readProcessStdout()));
    connect(m_process, SIGNAL(finished(int, QProcess::ExitStatus)), &m_generator, SLOT(widgetFilesCopied(int, QProcess::ExitStatus)));

    QStringList arguments;
    arguments  << "-xo" << params[0] << "-d" << params[1];

    startProcess(UNZIP_APP_NAME, arguments);
}

